package exporthandler

import (
	"archive/zip"
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"log"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
	"yundian/internel/app/dao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/helper/resphelper/placeresp"
	"yundian/internel/app/logic"
	"yundian/internel/app/models/cashlog"
	"yundian/internel/app/models/devices"
	"yundian/internel/app/models/liveservicelog"
	"yundian/internel/app/models/orders"
	"yundian/internel/app/models/placeincome"
	"yundian/internel/app/models/placemodel"
	"yundian/internel/app/models/refunds"
	"yundian/internel/app/models/reports"
	"yundian/internel/app/models/scanlogs"
	"yundian/internel/app/models/statistics"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	. "yundian/internel/pkg/dingo/result"
	"yundian/internel/pkg/export"
)

//订单导出
func HandelOrderExport(ctx *gin.Context) {
	loginUserId, err := helper.GetUserIdFromCtx(ctx) // 获取当前登录用户ID
	isAdmin, err := helper.GetIsAdminFromCtx(ctx)    // 从上下文中获取用户是否为管理员
	parentId, err := helper.GetParentIdFromCtx(ctx)  // 从上下文中获取当前用户的上级ID
	isPlace, err := helper.GetIsPlaceFromCtx(ctx)
	IsDraw, err := helper.GetIsDrawFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	// 请求参数处理
	param := &request.OrderListReq{}
	param.LoginUserId = loginUserId
	param.IsAdmin = isAdmin
	param.IsPlace = isPlace
	param.ParentId = parentId
	param.IsDraw = IsDraw
	dingo.ErrorIf(ctx.Bind(param)).Unwrap()

	if helper.IsAdminAndStaff(isAdmin, parentId) {
		param.LoginUserId = 2
	}

	// 查询结果
	data := dao.NewOrderDao().GetOrderList(param, 1)
	lists := data.Unwrap().([]*orders.OrderList)

	var newFileName = "order-" + time.Now().Format("2006-01-02-15-04-05") + ".xlsx"
	_, errByWriteExcel := export.OrderDataWriteTplExcel(lists, "订单列表", global.Cfg.Export.ExportPath+"template_order.xlsx", global.Cfg.Export.ExportExcel+newFileName)
	if errByWriteExcel != nil {
		Response(ctx)(errByWriteExcel.Error(), CodeSuccess, newFileName)(OK)
	}
	dingo.Task(logic.NewLogsLogic().InsertDownloadLog, func() {}, loginUserId, ctx.ClientIP(), newFileName, global.Cfg.Export.ExportExcel+newFileName, "订单数据导出")

	Response(ctx)("", CodeSuccess, newFileName)(OK)
	return
	//var newFileName = "order-list-" + time.Now().Format("2006-01-02-15-04-05") + ".csv"
	//e := export.OrderListExport(lists, global.Cfg.Export.ExportExcel+newFileName)
	//if e != nil {
	//	Response(ctx)(e.Error(), CodeError, newFileName)(OK)
	//	return
	//}
	//dingo.Task(logic.NewLogsLogic().InsertDownloadLog, func() {}, loginUserId, ctx.ClientIP(), newFileName, global.Cfg.Export.ExportExcel+newFileName, "订单数据导出")
	//
	//Response(ctx)("", CodeSuccess, newFileName)(OK)
	//return

}

//订单导出
func HandelOrderKfExport(ctx *gin.Context) {
	loginUserId, err := helper.GetUserIdFromCtx(ctx) // 获取当前登录用户ID
	isAdmin, err := helper.GetIsAdminFromCtx(ctx)    // 从上下文中获取用户是否为管理员
	parentId, err := helper.GetParentIdFromCtx(ctx)  // 从上下文中获取当前用户的上级ID
	isPlace, err := helper.GetIsPlaceFromCtx(ctx)
	IsDraw, err := helper.GetIsDrawFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	// 请求参数处理
	param := &request.OrderListReq{}
	param.LoginUserId = loginUserId // 当前登录用户ID
	param.IsAdmin = isAdmin         //角色类型 1:管理员 2:运营商 3:代理、商户 4:员工  5:合伙人
	param.IsPlace = isPlace
	param.ParentId = parentId // 当前登录账号的，上级ID
	param.IsDraw = IsDraw
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	// 查询结果
	data := dao.NewOrderDao().ExportOrderListKf(param)
	lists := data.Unwrap().([]*orders.OrderList)

	var newFileName = "order-list-" + time.Now().Format("2006-01-02-15-04-05") + ".csv"
	e := export.OrderListKfExport(lists, global.Cfg.Export.ExportExcel+newFileName)
	if e != nil {
		Response(ctx)(e.Error(), CodeError, newFileName)(OK)
		return
	}
	//var newFileName = "order-" + time.Now().Format("2006-01-02-15-04-05") + ".xlsx"
	//_, errByWriteExcel := export.OrderDataWriteTplExcelToKf(lists, "订单列表", global.Cfg.Export.ExportPath+"templatekf_order.xlsx", global.Cfg.Export.ExportExcel+newFileName)
	//if errByWriteExcel != nil {
	//	Response(ctx)(errByWriteExcel.Error(), CodeSuccess, newFileName)(OK)
	//}
	dingo.Task(logic.NewLogsLogic().InsertDownloadLog, func() {}, loginUserId, ctx.ClientIP(), newFileName, global.Cfg.Export.ExportExcel+newFileName, "订单数据导出(客服)")

	Response(ctx)("", CodeSuccess, newFileName)(OK)
	return
}

//退款列表
func HandelRefundExport(c *gin.Context) {
	loginUserId, _ := helper.GetUserIdFromCtx(c) // 获取当前登录用户ID
	// 请求参数处理
	param := &request.RefundListReq{}
	dingo.ErrorIf(c.ShouldBindQuery(param)).Unwrap()

	// 查询结果
	data := dao.NewRefundDao().GetRefundListInfo(param).Unwrap().([]*refunds.RefundModel)

	var newFileName = "refund-" + time.Now().Format("2006-01-02-15-04-05") + ".xlsx"

	_, errByWriteExcel := export.RefundDataWriteTplExcel(data, "退款列表", global.Cfg.Export.ExportPath+"template_refund.xlsx", global.Cfg.Export.ExportExcel+newFileName)
	if errByWriteExcel != nil {
		log.Println("退款列表导出失败：", errByWriteExcel.Error())
		//success
		Response(c)(errByWriteExcel.Error(), CodeSuccess, newFileName)(OK)

	}

	//c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%s", newFileName))
	//c.Writer.Header().Add("Content-Type", "application/octet-stream")
	//c.File(global.Cfg.Export.ExportExcel + newFileName)
	dingo.Task(logic.NewLogsLogic().InsertDownloadLog, func() {}, loginUserId, c.ClientIP(), newFileName, global.Cfg.Export.ExportExcel+newFileName, "退款列表导出")

	Response(c)("", CodeSuccess, newFileName)(OK)
	return
}

//故障列表列表
func HandelRepairExport(c *gin.Context) {
	userId, _ := helper.GetUserIdFromCtx(c)
	// 请求参数处理
	param := &request.ReportListReq{}
	dingo.ErrorIf(c.ShouldBindQuery(param)).Unwrap()

	// 查询结果
	data := dao.NewReportDao().GetReportList(param).Unwrap().([]*reports.ReportList)

	var newFileName = "repair-" + time.Now().Format("2006-01-02-15-04-05") + ".xlsx"

	_, errByWriteExcel := export.RepairDataWriteTplExcel(data, "故障列表", global.Cfg.Export.ExportPath+"template_repair.xlsx", global.Cfg.Export.ExportExcel+newFileName)
	if errByWriteExcel != nil {
		log.Println("故障列表导出失败：", errByWriteExcel.Error())
		//success
		Response(c)(errByWriteExcel.Error(), CodeSuccess, newFileName)(OK)

	}
	dingo.Task(logic.NewLogsLogic().InsertDownloadLog, func() {}, userId, c.ClientIP(), newFileName, global.Cfg.Export.ExportExcel+newFileName, "故障列表导出")

	Response(c)("", CodeSuccess, newFileName)(OK)
	return
}

//代理提现导出
func HandelAgentCashExport(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	dingo.ErrorIf(err).Unwrap()
	//userId := 127
	isAdmin, err := helper.GetIsAdminFromCtx(c)
	dingo.ErrorIf(err).Unwrap()

	// 请求参数处理
	param := &request.CashListReq{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	param.UserId = userId
	param.IsAdmin = int(isAdmin)
	// 查询结果
	data := dao.NewCashDao().GetQrCodeCashList(param).Unwrap().([]*cashlog.UserWithdrawalLog)

	var newFileName = "agentCash-" + time.Now().Format("2006-01-02-15-04-05") + ".xlsx"

	_, errByWriteExcel := export.AgentCashWriteTplExcel(data, "代理提现", global.Cfg.Export.ExportPath+"template_agent_cash.xlsx", global.Cfg.Export.ExportExcel+newFileName)
	if errByWriteExcel != nil {
		log.Println("代理提现列表导出失败：", errByWriteExcel.Error())
		//success
		Response(c)(errByWriteExcel.Error(), CodeSuccess, newFileName)(OK)

	}
	dingo.Task(logic.NewLogsLogic().InsertDownloadLog, func() {}, userId, c.ClientIP(), newFileName, global.Cfg.Export.ExportExcel+newFileName, "提现列表导出")

	Response(c)("", CodeSuccess, newFileName)(OK)
	return
}

// 分公司用户
func HandelBranchUserListExport(c *gin.Context) {
	// 请求参数处理
	param := &request.UserList{}
	dingo.ErrorIf(c.ShouldBindQuery(param)).Unwrap()
	param.ParentId = 2 // 默认为
	param.IsAdmin = helper.TypeNumIsAdminBranch
	//param.IsPlace = 3
	// 查询结果
	data := dao.NewUserDao().GetBranchUserList(param).Unwrap().([]*users.UserInfoWithKA)

	var newFileName = "branchUser-" + time.Now().Format("2006-01-02-15-04-05") + ".xlsx"

	_, errByWriteExcel := export.BranchUserListWriteTplExcel(data, "分公司用户", global.Cfg.Export.ExportPath+"template_branch_user.xlsx", global.Cfg.Export.ExportExcel+newFileName)
	if errByWriteExcel != nil {
		log.Println("分公司用户列表导出失败：", errByWriteExcel.Error())
		//success
		Response(c)(errByWriteExcel.Error(), CodeSuccess, newFileName)(OK)

	}
	Response(c)("", CodeSuccess, newFileName)(OK)
	return
}

//网点导出
func HandelPlacesExport(ctx *gin.Context) {
	param := &request.PlacesListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	loginUserId, err := helper.GetUserIdFromCtx(ctx) // 获取当前代理商ID
	isAdmin, _ := helper.GetIsAdminFromCtx(ctx)
	parentId, _ := helper.GetParentIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	// 超级管理员 && 运营商下的员工
	if helper.IsAdminAndStaff(isAdmin, parentId) {
		loginUserId = 2
	}

	data := dao.NewPlaceDao().GetPlaceList(param, loginUserId)
	lists := data.Unwrap().([]*placeresp.PlaceList) // 门店列表

	var newFileName = "places-" + time.Now().Format("2006-01-02-15-04-05") + ".xlsx"
	_, errByWriteExcel := export.PlacesDataWriteTplExcel(lists, "网点列表", global.Cfg.Export.ExportPath+"template_places.xlsx", global.Cfg.Export.ExportExcel+newFileName, int(isAdmin))
	if errByWriteExcel != nil {
		log.Println("订单导出失败：", errByWriteExcel.Error())
		Response(ctx)(errByWriteExcel.Error(), CodeSuccess, newFileName)(OK)
		return
	}
	dingo.Task(logic.NewLogsLogic().InsertDownloadLog, func() {}, loginUserId, ctx.ClientIP(), newFileName, global.Cfg.Export.ExportExcel+newFileName, "门店列表导出")

	Response(ctx)("", CodeSuccess, newFileName)(OK)
	return
}

//门店操作日志导出
func HandlePlaceOperateLog(ctx *gin.Context) {
	param := &request.PlaceOperateLogReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	loginUserId, err := helper.GetUserIdFromCtx(ctx) // 获取当前代理商ID
	dingo.ErrorIf(err).Unwrap()

	data := dao.NewUserDao().GetPlaceOperateLog(param)
	lists := data.Unwrap().([]placemodel.PlaceOperateLog) // 门店列表

	var newFileName = "placesOperateLog-" + time.Now().Format("2006-01-02-15-04-05") + ".xlsx"
	_, errByWriteExcel := export.PlacesOperateLogWriteTplExcel(lists, "门店更新日志", global.Cfg.Export.ExportPath+"template_place_operate_log.xlsx", global.Cfg.Export.ExportExcel+newFileName)
	if errByWriteExcel != nil {
		log.Println("订单导出失败：", errByWriteExcel.Error())
		Response(ctx)(errByWriteExcel.Error(), CodeSuccess, newFileName)(OK)
		return
	}
	dingo.Task(logic.NewLogsLogic().InsertDownloadLog, func() {}, loginUserId, ctx.ClientIP(), newFileName, global.Cfg.Export.ExportExcel+newFileName, "门店操作日志导出")

	Response(ctx)("", CodeSuccess, newFileName)(OK)
	return
}

//网点导出
func HandelSmallPlacePloyExport(ctx *gin.Context) {
	loginUserId, _ := helper.GetUserIdFromCtx(ctx)
	param := &request.PlacesListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	data := dao.NewPlaceDao().GetAllPlaceList(param)
	lists := data.Unwrap().([]*placeresp.PlaceListByAll) // 门店列表

	var newFileName = "smallplaces-" + time.Now().Format("2006-01-02-15-04-05") + ".xlsx"
	_, errByWriteExcel := export.SmallPlacePloyDataWriteTplExcel(lists, "网点列表", global.Cfg.Export.ExportPath+"template_small_place_ploy.xlsx", global.Cfg.Export.ExportExcel+newFileName)
	if errByWriteExcel != nil {
		log.Println("订单导出失败：", errByWriteExcel.Error())
		Response(ctx)(errByWriteExcel.Error(), CodeSuccess, newFileName)(OK)
		return
	}
	dingo.Task(logic.NewLogsLogic().InsertDownloadLog, func() {}, loginUserId, ctx.ClientIP(), newFileName, global.Cfg.Export.ExportExcel+newFileName, "奖励列表(small)导出")

	Response(ctx)("", CodeSuccess, newFileName)(OK)
	return
}

func HandelPlacePloyExport(ctx *gin.Context) {
	param := &request.PlacesListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	data := dao.NewPlaceDao().GetAllPlaceList(param)
	lists := data.Unwrap().([]*placeresp.PlaceListByAll) // 门店列表

	var newFileName = "places-" + time.Now().Format("2006-01-02-15-04-05") + ".xlsx"
	_, errByWriteExcel := export.PlacePloyDataWriteTplExcel(lists, "网点列表", global.Cfg.Export.ExportPath+"template_place_ploy.xlsx", global.Cfg.Export.ExportExcel+newFileName)
	if errByWriteExcel != nil {
		log.Println("订单导出失败：", errByWriteExcel.Error())
		Response(ctx)(errByWriteExcel.Error(), CodeSuccess, newFileName)(OK)
		return
	}

	Response(ctx)("", CodeSuccess, newFileName)(OK)
	return
}

// 客户扫码导出
func HandleQrLogsExport(ctx *gin.Context) {
	param := &request.ScanLogsListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	data := dao.NewScanLogsDao().GetScanLogsList(param)
	lists := data.Unwrap().([]scanlogs.ScanLogsModel)

	var newFileName = "scan-log-" + time.Now().Format("2006-01-02-15-04-05") + ".csv"
	err := export.ScanLogExport(lists, global.Cfg.Export.ExportExcel+newFileName)
	if err != nil {
		Response(ctx)(err.Error(), CodeError, newFileName)(OK)
		return
	}

	Response(ctx)("", CodeSuccess, newFileName)(OK)
	return
}

// 服务日志点击导出
func HandleServiceClickExport(ctx *gin.Context) {
	param := &request.ServiceClickLogsListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	data := dao.NewLiveServiceLogDao().GetLiveServiceLogList(param)
	lists := data.Unwrap().([]liveservicelog.ServiceLogList) // 门店列表

	var newFileName = "service-click-log-" + time.Now().Format("2006-01-02-15-04-05") + ".csv"
	err := export.ServiceClickExport(lists, global.Cfg.Export.ExportExcel+newFileName)
	if err != nil {
		Response(ctx)(err.Error(), CodeError, newFileName)(OK)
		return
	}

	Response(ctx)("", CodeSuccess, newFileName)(OK)
	return
}

//设备导出
func HandelDeviceExport(ctx *gin.Context) {
	// 请求参数处理
	param := &request.DeviceListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	loginUserId, err := helper.GetUserIdFromCtx(ctx) // 获取当前登录用户ID
	isAdmin, _ := helper.GetIsAdminFromCtx(ctx) // 从上下文中获取用户是否为管理员
	parentId, _ := helper.GetParentIdFromCtx(ctx) // 从上下文中获取当前登录用户的上级ID
	IsPlace, _ := helper.GetIsPlaceFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	param.IsPlace = IsPlace
	param.LoginUserId = loginUserId // 当前登录用户ID
	param.IsAdmin = isAdmin         //角色类型 1:管理员 2:运营商 3:代理、商户 4:员工  5:合伙人

	if helper.IsAdminAndStaff(isAdmin, parentId) {
		param.IsAdmin = helper.TypeNumIsAdminOperator
		param.LoginUserId = 2
	}

	// 获取数据
	data := dao.NewDeviceDao().FetchDeviceListWithType(param)
	lists := data.Unwrap().([]*devices.DeviceType)

	var newFileName = "device-" + time.Now().Format("2006-01-02-15-04-05") + ".xlsx"
	_, errByWriteExcel := export.DeviceDataWriteTplExcel(lists, "密码线充", global.Cfg.Export.ExportPath+"template_device.xlsx", global.Cfg.Export.ExportExcel+newFileName)
	if errByWriteExcel != nil {
		log.Println("设备导出失败：", errByWriteExcel.Error())
		Response(ctx)(errByWriteExcel.Error(), CodeSuccess, newFileName)(OK)
	}
	dingo.Task(logic.NewLogsLogic().InsertDownloadLog, func() {}, loginUserId, ctx.ClientIP(), newFileName, global.Cfg.Export.ExportExcel+newFileName, "设备列表导出")

	Response(ctx)("", CodeSuccess, newFileName)(OK)
	return
}

//网点统计导出
func HandelPlaceTotalExport(c *gin.Context) {
	loginUserId, err := helper.GetUserIdFromCtx(c) // 获取当前代理商ID
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	isAdmin, err := helper.GetIsAdminFromCtx(c) // 从上下文中获取用户是否为管理员
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	IsDraw, err := helper.GetIsDrawFromCtx(c) // 从上下文中获取
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	parentId, _ := helper.GetParentIdFromCtx(c)

	param := &struct {
		PlaceName   string `json:"placeName" form:"placeName" `
		SelectTime  string `json:"selectTime" form:"selectTime"`
		MonthType   int    `json:"type" form:"type"`
		SharedMode  string `json:"sharedMode" form:"sharedMode"`
		BaseListReq request.BaseListReq
	}{}

	dingo.ErrorIf(c.Bind(param)).Unwrap()
	//loginUserId = 719
	//loginUserId := 2
	//var isAdmin uint8
	//isAdmin = 2
	var lists []*placeincome.PlaceIncomeExportModel

	if isAdmin == helper.TypeNumIsAdminAdministrator || (isAdmin == helper.TypeNumIsAdminStaff && parentId == 2) {
		loginUserId = 2
		isAdmin = helper.TypeNumIsAdminAdministrator
	}

	if param.MonthType == 3 {
		data := dao.NewStatisticalDao().
			PlaceStatisticsExportAllTotalListDao(loginUserId, isAdmin, IsDraw, param.PlaceName, &param.BaseListReq)
		lists = data.Unwrap().([]*placeincome.PlaceIncomeExportModel)
	} else if param.MonthType == 2 {
		data := dao.NewStatisticalDao().
			PlaceStatisticsExportMonthListDao(loginUserId, isAdmin, IsDraw, param.PlaceName, param.SelectTime, &param.BaseListReq)
		lists = data.Unwrap().([]*placeincome.PlaceIncomeExportModel)

	} else {
		data := dao.NewStatisticalDao().
			PlaceStatisticsExportListDao(loginUserId, isAdmin, param.PlaceName, param.SelectTime,
				param.MonthType, param.SharedMode, &param.BaseListReq)
		lists = data.Unwrap().([]*placeincome.PlaceIncomeExportModel)
	}

	if param.MonthType != 3 {
		userIdArr := dao.NewUserDao().QueryChildUserIds(loginUserId).Unwrap().([]int)
		placeIdArr := dao.NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		activeDevCountMap := make(map[string]int64)
		var activeDevCountModel []devices.ActiveDeviceCount
		//查询所有有产设备量数据
		if param.SelectTime == "" {
			activeDevCountModel = dao.NewDeviceDao().GetActiveDevCount(placeIdArr, 0, 0).Unwrap().([]devices.ActiveDeviceCount)
		} else {
			selectTimeArr := strings.Split(param.SelectTime, ",")
			startTime, _ := strconv.Atoi(selectTimeArr[0])
			endTime, _ := strconv.Atoi(selectTimeArr[1])
			activeDevCountModel = dao.NewDeviceDao().GetActiveDevCount(placeIdArr, startTime, endTime).Unwrap().([]devices.ActiveDeviceCount)
		}

		for _, v := range activeDevCountModel {
			activeDevCountMap[v.Date+"-"+strconv.Itoa(v.PlaceId)] = v.Total
		}

		for _, lst := range lists {
			lst.ScanCount = lst.OrderCount
			lst.DeviceCount = lst.DeviceTotal
			// 有产设备量

			if v, ok := activeDevCountMap[lst.IncomeDay+"-"+strconv.Itoa(lst.PlaceId)]; ok {
				lst.ActiveDevCount = v
			} else {
				lst.ActiveDevCount = 0
			}
		}
	}
	var newFileName = "place-total-" + time.Now().Format("2006-01-02-15-04-05") + ".xlsx"

	//网点统计导出
	_, errByWriteExcel := export.PlaceTotalWriteTplExcel(lists, "网点统计", global.Cfg.Export.ExportPath+"template_place_total.xlsx", global.Cfg.Export.ExportExcel+newFileName, param.MonthType)
	if errByWriteExcel != nil {
		log.Println("订单导出失败：", errByWriteExcel.Error())
		//success
		Response(c)(errByWriteExcel.Error(), CodeSuccess, newFileName)(OK)

	}

	Response(c)("", CodeSuccess, newFileName)(OK)
	return
}

//网点评级导出
func HandlePlaceLevelLogExport(ctx *gin.Context) {
	// 请求参数处理
	param := &request.PlacesLevelListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	loginUserId, err := helper.GetUserIdFromCtx(ctx) // 获取当前代理商ID
	isAdmin, err := helper.GetIsAdminFromCtx(ctx)
	parentId, err := helper.GetParentIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	if isAdmin == helper.TypeNumIsAdminAdministrator || (isAdmin == helper.TypeNumIsAdminStaff && parentId == 2) {
		loginUserId = 2
	}

	data := dao.NewPlaceDao().GetPlaceLevelLogList(param, loginUserId)
	lists := data.Unwrap().([]*placemodel.PlaceLevelLogModel)

	var newFileName = "place-level-log-" + time.Now().Format("2006-01-02-15-04-05") + ".xlsx"
	_, errByWriteExcel := export.PlaceLevelLogExport(lists, "门店评级", global.Cfg.Export.ExportPath+"template_place_level_log.xlsx", global.Cfg.Export.ExportExcel+newFileName)
	if errByWriteExcel != nil {
		log.Println("订单导出失败：", errByWriteExcel.Error())
		Response(ctx)(errByWriteExcel.Error(), CodeSuccess, newFileName)(OK)
	}
	log.Println(newFileName)
	Response(ctx)("", CodeSuccess, newFileName)(OK)
	return
}

//用户统计导出
func HandleUsersTotalExport(c *gin.Context) {

	//param := &request.AgentStatisticsReportReq{}
	//dingo.ErrorIf(c.Bind(param)).Unwrap()
	//
	//loginUserId, err := helper.GetUserIdFromCtx(c) // 获取当前代理商ID
	//if err != nil {
	//	Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
	//	return
	//}
	//isAdmin, _ := helper.GetIsAdminFromCtx(c)
	//
	//param.LoginUserId = loginUserId
	//param.IsAdmin = isAdmin
	//
	////param.LoginUserId = 217
	////param.IsAdmin = 5
	//
	////if param.UserId == 0 {
	////	param.UserId = loginUserId
	////}
	//
	//data := dao.NewStatisticalDao().AgentIncomeDayStatisticsListExport(param).Unwrap().([]*agentincome.AgentIncomeModel)
	//
	//var newFileName = "user-total-" + time.Now().Format("2006-01-02-15-04-05") + ".xlsx"
	//
	////用户统计导出
	//_, errByWriteExcel := export.UserTotalWriteTplExport(data, "用户统计", global.Cfg.Export.ExportExcel+newFileName)
	//if errByWriteExcel != nil {
	//	log.Println("订单导出失败：", errByWriteExcel.Error())
	//	//success
	//	Response(c)(errByWriteExcel.Error(), CodeSuccess, newFileName)(OK)
	//
	//}
	//
	//Response(c)("", CodeSuccess, newFileName)(OK)
	//return
}

//文件下载
func DownloadExportExcel(c *gin.Context) {
	param := &struct {
		NewFileName string `json:"fileName" form:"fileName"`
	}{}
	dingo.ErrorIf(c.ShouldBindQuery(param)).Unwrap()
	if param.NewFileName == "" {
		Response(c)("参数不能为空", CodeSuccess, "")(OK)
	}

	c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%s", param.NewFileName))
	c.Writer.Header().Add("Content-Type", "application/octet-stream")
	c.File(global.Cfg.Export.ExportExcel + param.NewFileName)
	return
}

//func HanderDownload(c *gin.Context) {
//
//	loginUserId := 0
//	// 请求参数处理
//	param := &request.OrderListReq{}
//	param.LoginUserId = 2
//	param.IsAdmin = uint8(2)
//	param.IsPlace = uint8(0)
//	param.ParentId = 0
//	param.IsDraw = uint8(1)
//	dingo.ErrorIf(c.Bind(param)).Unwrap()
//
//	userNoMap := make(map[int]string)
//
//	userIdArr := dao.NewUserDao().QueryChildUserIds(loginUserId).Unwrap().([]int)
//	placeIdArr := dao.NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
//	userNoList := dao.NewUserDao().GetUserNoByPlaceIds(placeIdArr).Unwrap().([]users.UserNoByPlaceIds)
//	//总收益封装map
//	for _, v := range userNoList {
//		userNoMap[v.PlaceId] = v.UserNo
//	}
//
//	placeHotelIdMap := make(map[int]string)
//	PlaceHotelIdModel := dao.NewPlaceDao().GetPlaceHotelId(placeIdArr).Unwrap().([]placeresp.PlaceHotelIdExport)
//
//	// 获取 携程母酒店ID
//	for _, v := range PlaceHotelIdModel {
//		placeHotelIdMap[v.PlaceId] = v.HotelId
//	}
//
//	var lists []*orders.OrderExportModel
//	param.CountStatus = helper.TypeNumCountStatusNo
//	data := dao.NewOrderDao().GetOrderList(param)
//	orderLists := data.Unwrap().([]*orders.OrderModel)
//
//	for _, item := range orderLists {
//		lst := &orders.OrderExportModel{
//			IsDraw:          int(item.IsDraw),
//			TradeNo:         item.TradeNo,
//			OutTradeNo:      item.OutTradeNo,
//			State:           item.State,
//			MemberName:      item.MemberName,
//			OrderFrom:       item.OrderFrom,
//			PlaceId:         item.PlaceId,
//			PlaceName:       item.PlaceName,
//			DeviceSn:        item.DeviceSn,
//			PayMoney:        item.PayMoney,
//			SettlementMoney: item.SettlementMoney,
//			TradeStateDesc:  item.TradeStateDesc,
//			Phone:           item.Phone,
//			UserId:          item.UserId,
//			UserName:        item.UserName,
//			UserNo:          item.UserNo,
//			MemberPhone:     item.MemberPhone,
//			CreateAt:        item.CreateAt,
//			EndAt:           item.EndAt,
//			CouponType:      int(item.CouponType),
//			CouponMoney:     item.CouponMoney,
//			IsTianHai:       int(item.IsTianHai),
//			HotelId:         "",
//		}
//		if v, ok := userNoMap[lst.PlaceId]; ok {
//			item.UserNo = v
//		}
//		lst.MemberName = helper.GetPhoneStr(lst.MemberName)
//		lst.MemberPhone = helper.GetPhoneStr(lst.MemberPhone)
//		if lst.Phone == lst.UserName {
//			lst.UserName = helper.GetPhoneStr(lst.UserName)
//		}
//		if v, ok := placeHotelIdMap[lst.PlaceId]; ok {
//			lst.HotelId = v
//		}
//		lists = append(lists, lst)
//	}
//
//	index := "2"
//	log.Println("当前登录的用户Id", loginUserId)
//
//	//templateFile := "./static/excel_template/template_order.xls"
//
//	log.Println("当前登录的用户Id", loginUserId)
//	var newFileName = global.Cfg.Export.ExportExcel + "order-" + time.Now().Format("2006-01-02-15-04-05")
//
//	err := os.MkdirAll(newFileName, os.ModePerm)
//	if err != nil {
//		log.Println("订单导出失败：", err.Error())
//		Response(c)(err.Error(), CodeError, newFileName)(OK)
//		return
//	}
//
//	_, errByWriteExcel := export.OrderDataIsAdminWriteTplExcel(lists, "订单列表", global.Cfg.Export.ExportPath+"template_order.xlsx", newFileName, index)
//	if errByWriteExcel != nil {
//		log.Println("订单导出失败：", errByWriteExcel.Error())
//		//success
//		Response(c)(errByWriteExcel.Error(), CodeSuccess, newFileName)(OK)
//
//	}
//	zipFile := global.Cfg.Export.ExportExcel + time.Now().Format("2006-01-02-15-04-05") + ".zip"
//	err = FileZip(newFileName, zipFile)
//	if err != nil {
//		log.Println("订单导出失败：", err.Error())
//		Response(c)(err.Error(), CodeError, newFileName)(OK)
//		return
//	}
//	Response(c)("", CodeSuccess, zipFile)(OK)
//
//}

func FileZip(srcFile string, destZip string) error {
	zipfile, err := os.Create(destZip)
	if err != nil {
		return err
	}
	defer zipfile.Close()

	archive := zip.NewWriter(zipfile)
	defer archive.Close()

	filepath.Walk(srcFile, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		header, err := zip.FileInfoHeader(info)
		if err != nil {
			return err
		}

		header.Name = strings.TrimPrefix(path, filepath.Dir(srcFile)+"/")
		// header.Name = path
		if info.IsDir() {
			header.Name += "/"
		} else {
			header.Method = zip.Deflate
		}

		writer, err := archive.CreateHeader(header)
		if err != nil {
			return err
		}

		if !info.IsDir() {
			file, err := os.Open(path)
			if err != nil {
				return err
			}
			defer file.Close()
			_, err = io.Copy(writer, file)
		}
		return err
	})

	return err
}

func HandelPartnerUserStatisticsListExport(ctx *gin.Context) {
	param := &request.UserAnalysisListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	loginUserId, err := helper.GetUserIdFromCtx(ctx)
	isAdmin, _ := helper.GetIsAdminFromCtx(ctx)
	parentId, _ := helper.GetParentIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	// 超级管理员 && 运营商下的员工 才可下载
	if b := helper.IsAdminAndStaff(isAdmin, parentId); b {
		data := dao.NewStatisticsDao().GetUserAnalysisList(param)
		lists := data.Unwrap().([]*statistics.StatisticsUserList)

		var newFileName = "partnerUserStatistics-" + time.Now().Format("2006-01-02-15-04-05") + ".xlsx"
		_, errByWriteExcel := export.ExportPartnerUserAnalysisList(lists, "列表", global.Cfg.Export.ExportPath+"template_partner_user_statistics.xlsx", global.Cfg.Export.ExportExcel+newFileName)
		if errByWriteExcel != nil {
			log.Println("导出失败：", errByWriteExcel.Error())
			Response(ctx)(errByWriteExcel.Error(), CodeSuccess, newFileName)(OK)
			return
		}
		dingo.Task(logic.NewLogsLogic().InsertDownloadLog, func() {}, loginUserId, ctx.ClientIP(), newFileName, global.Cfg.Export.ExportExcel+newFileName, "合伙人分析数据列表导出")

		Response(ctx)("导出成功", CodeSuccess, newFileName)(OK)
		return
	} else {
		Response(ctx)("没有权限", CodeSuccess, false)(OK)
		return
	}
}
